---
import { render, type CollectionEntry } from 'astro:content'
import RightSidebarInner from './RightSidebar.svelte'
import { getGithubEditUrl } from '$lib/getGithubEditUrl'

interface Props {
  entry: CollectionEntry<'learn'> | CollectionEntry<'reference'>
}

const { entry } = Astro.props

const content = await render(entry)

// we're only showing headings with depth 2 and 3 in the sidebar
const showHeadingsWithDepth = [2, 3]
const headings = [...content.headings].filter((heading) =>
  showHeadingsWithDepth.includes(heading.depth)
)

const entryIsReference = (e: typeof entry): e is CollectionEntry<'reference'> => {
  return (e && e.data && (e.data as any)).schemaType === 'reference'
}

if (entryIsReference(entry) && entry.data.componentSignature) {
  const hasEvents = !!entry.data.componentSignature.events?.length
  const hasProps = !!entry.data.componentSignature.props?.length
  const hasBindings = !!entry.data.componentSignature.bindings?.length

  if (hasEvents || hasProps || hasBindings) {
    // we're adding a new heading for the component signature
    // with the lowest depth of the filtered headings
    const lowestHeadingDepth = Math.min(...headings.map((heading) => heading.depth))
    headings.push({
      depth: lowestHeadingDepth,
      slug: 'component-signature',
      text: 'Component Signature'
    })
  }
}

const editUrl = getGithubEditUrl(Astro)

const sourceUrl =
  entryIsReference(entry) && entry.data.sourcePath
    ? `https://github.com/threlte/threlte/blob/main/${entry.data.sourcePath}`
    : undefined
---

<RightSidebarInner
  client:idle
  {headings}
  {entry}
  {editUrl}
  {sourceUrl}
>
  <slot />
</RightSidebarInner>
